/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lidroid.xutils_sample.slice;


import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils_sample.ResourceTable;
import com.lidroid.xutils_sample.bean.User;


import com.lidroid.xutils.exception.DbException;
import ohos.aafwk.ability.AbilitySlice;

import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;


import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

public class DbUtilsPageSlice extends AbilitySlice {

//    @ViewInject(id=ResourceTable.Id_btn_view_utils,click="btnViewClick") Button btnView;
//    @ViewInject(id=ResourceTable.Id_btn_view_utils) Text textViews;

    static  final HiLogLabel lable = new HiLogLabel(HiLog.LOG_APP,0x00201,"MainAbility");

    @Override
    public void onStart(Intent intent) {
        Button btnSet,btnGet,btnDel,btnUpdate;
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_db_utils_page);
        btnSet=(Button)findComponentById(ResourceTable.Id_btn_set);
        btnGet=(Button)findComponentById(ResourceTable.Id_btn_get);
        btnDel=(Button)findComponentById(ResourceTable.Id_btn_del);
        btnUpdate=(Button)findComponentById(ResourceTable.Id_btn_update);
        // update
        btnUpdate.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    btnUpdateClick();
                } catch (DbException e) {
                    HiLog.error(lable, e.toString());
                }
            }
        });
        // 增
        btnSet.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    btnSetClick();
                    toast("添加成功");
                } catch (Exception e) {
                    HiLog.error(lable, e.toString());
                }
            }
        });
        // 查
        btnGet.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                try {
                    btnGetClick();
                } catch (DbException e) {
                    HiLog.error(lable, e.toString());
                }

            }
        });
        //删
        btnDel.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    btnDelClick();
                } catch (DbException e) {
                    HiLog.error(lable, e.toString());
                }

            }
        });

    }

    public void btnUpdateClick() throws DbException {
        DbUtils db= DbUtils.create(this);
        List<User> all = db.findAll(User.class);
        int i=all.size();
        if(i==0){
            toast("没有数据，请添加数据再update");
        }else{
            DirectionalLayout titleLayout = (DirectionalLayout) LayoutScatter.getInstance(this)
                    .parse(ResourceTable.Layout_dialog_edit, null, false);
            final int width = 1000;
            new CommonDialog(getContext())
                    .setTitleCustomComponent(titleLayout)
                    .setButton(1, "ok", new IDialog.ClickedListener(){
                        @Override
                        public void onClick(IDialog iDialog, int i) {
                            Text updateId=(Text) titleLayout.findComponentById(ResourceTable.Id_update_id);
                            Text updateEmail=(Text) titleLayout.findComponentById(ResourceTable.Id_update_email);
                            Text updateName=(Text) titleLayout.findComponentById(ResourceTable.Id_update_name);
                            int id=-1;
                            if (updateId!=null)
                            {
                                try {
                                    id = Integer.parseInt(updateId.getText());
                                }

                                catch (Exception e)
                                {
                                    new ToastDialog(getContext()).setText("输入数值").show();
                                }
                            }
                            String email=updateEmail.getText().toString();
                            String name=updateName.getText().toString();
                            try {
                                if(id!=-1&&email!=null&&name!=null) {
                                    updateById(id,email,name);
                                }
                            } catch (DbException e) {
                                HiLog.error(lable, e.toString());
                            }
                            toast("id为"+id+"的数据修改成功");
                            iDialog.destroy();
                        }
                    })
                    .setButton(0, "cancel", new IDialog.ClickedListener(){
                        @Override
                        public void onClick(IDialog iDialog, int i) {
                            iDialog.destroy();
                        }
                    })
                    .setSize(width,MATCH_CONTENT)
                    .show();


        }


    }
    public void updateById(int id, String email, String name) throws DbException {
        DbUtils db= DbUtils.create(this);
        User user = new User();
        user.setId(id);
        user.setEmail(email);
        user.setName(name);
        db.update(user);
    }
    public void btnDelClick() throws DbException {
        DbUtils db= DbUtils.create(this);
        List<User> all = db.findAll(User.class);
        int i=all.size();
        if(i==0){
           toast("没有数据，请添加数据再删除");
        }else{
            final TextField editText = new TextField(this);
            // 输入框
            editText.setLayoutConfig(new ComponentContainer.LayoutConfig(MATCH_PARENT,MATCH_CONTENT));
            editText.setHint("请输入ID");
            final int textSize = 50;
            editText.setTextSize(textSize);
            final int left = 100;
            final int top = 10;
            final int rigth = 10;
            final int bottom = 70;
            editText.setPadding(left, top, rigth, bottom);

            final int width = 1000;
            new CommonDialog(getContext())
                    .setTitleText("根据id删除：")
                    .setContentCustomComponent(editText)
                    .setButton(1, "ok", new IDialog.ClickedListener(){
                        @Override
                        public void onClick(IDialog iDialog, int i) {

                            try {
                                int id=Integer.parseInt(editText.getText().toString());
                                delID(id);
                                toast("id为"+id+"的数据删除成功");
                            } catch (DbException e) {
                                HiLog.error(lable, e.toString());
                            }
                            catch (NumberFormatException e)
                            {
                               new  ToastDialog(getContext()).setText("请输入id").show();
                            }
                            iDialog.destroy();
                        }
                    })
                    .setSize(width,MATCH_CONTENT)
                    .show();
        }


    }

    public void delID(int id) throws DbException {
        DbUtils db= DbUtils.create(this);
            db.deleteById(User.class, id);

    }


    public void btnGetClick() throws DbException {
        DbUtils db= DbUtils.create(this);
        List<User> all = db.findAll(User.class);
        int i=all.size();
        if(i==0){
            toast("没有数据，请添加数据再查询");
        }else{
            StringBuffer uStrings = new StringBuffer() ;
            for (User u : all) {
                uStrings.append(u.toString());
                HiLog.info(lable, "users:" + u.toString());
            }
            // 自定义文本-因为原来的Text文字过多不换行
            DirectionalLayout titleLayout = (DirectionalLayout) LayoutScatter.getInstance(this)
                    .parse(ResourceTable.Layout_dialog_text, null, false);
            // 获取text 标签
            Text title=(Text) titleLayout.findComponentById(ResourceTable.Id_dialog_title);
            // 赋值
            title.setText(uStrings.toString());
            final int width = 1000;
            new CommonDialog(getContext())
                    .setTitleText("查询全部数据如下：")
                    .setContentCustomComponent(titleLayout)
                    .setSize(width,MATCH_CONTENT)
                    .show();
        }

    }

    //
    public void btnSetClick() throws DbException {
        TextField textEmail,textName;
//        textId=(TextField)findComponentById(ResourceTable.Id_edit_id) ;
        textEmail=(TextField)findComponentById(ResourceTable.Id_edit_email);
        textName=(TextField)findComponentById(ResourceTable.Id_edit_name);
//        int id=Integer.parseInt(textId.getText().toString());
        String name=textEmail.getText().toString();
        String email=textName.getText().toString();

        DbUtils db = DbUtils.create(this);
        User user = new User(); //这里需要注意的是User对象必须有id属性，或者有通过@ID注解的属性
//        user.setId(id);
        user.setEmail(email);
        user.setName(name);
        db.saveBindingId(user);// 使用saveBindingId保存实体时会为实体的id赋值
    }
    /**
     * 自定义toast
     * @param  string 弹出内容
     */
    public void toast(String string){
        // 自定义弹框标题-因为原来的titleText文字过多不换行
        DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_layout_toast, null, false);
        // 获取text 标签
        Text title=(Text) toastLayout.findComponentById(ResourceTable.Id_toast_content);
        // 赋值
        title.setText(string);
        new ToastDialog(getContext())
                .setComponent(toastLayout)
                .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .show();
    }
    @Override
    public void onActive() {
        super.onActive();
        HiLog.info(lable, "onActive");
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        HiLog.info(lable, "onForeground");
    }
}
